package com.gate.ws.spring.process.upmsg;

import cn.hutool.json.JSONUtil;
import com.gate.ws.spring.constants.ChannelConstants;
import com.gate.ws.spring.request.RpcConfig;
import com.gate.ws.spring.service.MqSender;
import com.nami.basic.bo.servicetrans.up.UpMsgWrap;
import com.nami.basic.constants.UpTopicConst;
import com.nami.basic.packet.Packet;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.dubbo.common.utils.NetUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

public class C2GProcess implements PacketProcessor {

    private static final Logger log = LoggerFactory.getLogger(C2GProcess.class);

    private RpcConfig rpcConfig;

    private MqSender mqSender;

    public C2GProcess(MqSender mqSender, RpcConfig rpcConfig) {
        this.mqSender = mqSender;
        this.rpcConfig = rpcConfig;
    }

    @Override
    public void process(Channel channel, Packet packet) throws Exception {
        try {
            if (channel == null) {
                log.warn("[c2g] channel is null. ");
                return;
            }
            mqSender.send(UpTopicConst.C2G_TOPIC, JSONUtil.toJsonStr(newC2GMSg(channel, packet)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @NotNull
    private UpMsgWrap newC2GMSg(Channel channel, Packet packet) {

        UpMsgWrap dto = new UpMsgWrap();
        dto.setDeviceType((Integer) channel.attr(AttributeKey.valueOf(ChannelConstants.DEVICE_TYPE)).get());
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();

        dto.setBindingUserId((String) channel.attr(AttributeKey.valueOf(ChannelConstants.USER_ID)).get());
        dto.setBindingAppKey((String) channel.attr(AttributeKey.valueOf(ChannelConstants.APP_KEY)).get());

        dto.setUserIp(socketAddress.getAddress().getHostAddress());
        dto.setMqTags(rpcConfig.getMqTags());
        dto.setDubboIp(NetUtils.getLocalHost());
        dto.setDubboPort(rpcConfig.getDubboPort());
        dto.setPacket(packet);
//        log.info("[upmsg] send to logic service. body:{}", ToStringBuilder.reflectionToString(dto, ToStringStyle.SHORT_PREFIX_STYLE));
        return dto;
    }


}
